﻿<!DOCTYPE HTML>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>HTML5 Worker</title>
</head>
<body>
    <h3>HTML5提供了Worker类用于多线程处理。</h3>
    <div style="border: 1px solid #000; padding: 20px;">
        <h3>普通累加计算：</h3>
        <input id="num" name="num" type="text" value="12345678" />
        <button onclick="calculate()">计算</button><br />
        <div id="result" style="color: red;"></div>
        <div id="time" style="color: red;"></div>
        <script type="text/javascript" src="calculate.js"></script>
        <script type="text/javascript">
            function calculate() {
                var num = document.getElementById("num").value;
                var val = parseInt(num, 10);
                var result = 0;
                var data1 = new Date().getTime();
                for (var i = 0; i < num; i++) {
                    result += i;
                }
                var data2 = new Date().getTime();
                document.getElementById("result").innerHTML = "计算结果：" + result;
                document.getElementById("time").innerHTML = "普通 耗时：" + (data2 - data1) / 1000 + "秒";
            }
        </script>
    </div>

    <div style="border: 1px solid #000; margin-top: 20px; padding: 20px;">
        <h3>HTML5 Worker累加计算：</h3>
        <input id="num2" name="num2" type="text"  value="12345678" />
        <button onclick="calculate2()">计算</button><br />
        <div id="result2" style="color: red;"></div>
        <div id="time2" style="color: red;"></div>
        <script type="text/javascript" src="calculate.js"></script>
        <script type="text/javascript">
            var worker = new Worker("worker.js");
            var d1 = 0;
            var d2 = 0;
            worker.onmessage = function (event) {
                var data = event.data;
                d2 = new Date().getTime();
                document.getElementById("result2").innerHTML = "计算结果：" + data;
                document.getElementById("time2").innerHTML = "workers 耗时：" + (d2 - d1)/1000 + "秒";
            };
            function calculate2() {
                var num2 = document.getElementById("num2").value * 1;
                d1 = new Date().getTime();
                worker.postMessage(num2);
            }
        </script>
    </div>
</body>
</html>
